// pages/scenorder/scenorder.js
var WxParse = require("../../../lib/wxParse/wxParse.js")
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var Data = require("../../../utils/data.js");
var Base64util = require("../../../utils/base64.js");
var app = getApp();
Page({
  data: {
    is_select_Hidden: true,
    is_modal_Msg: '我是一个自定义组件',
    date: '',
    tomorrow: '',
    dates: 2,
    roomnum: 1,
    tabclass: '',
    tabStatus: 0,
    index: [0,1,2],
    winWidth: 0,
    winHeight: 0,
    number: 1,
    date1: util.formatDay(new Date()),
    start: util.formatDay(new Date()),
    customerInfo: {},
    date: '',
    tomorrow: '',
    dates: 1,
    userList: [{id:"", name: "", tel: "", idCard: "" }],
    type: "",
    check: false,
    needBill: false,
    billInfo: {},
    couponList: [],
    coupon: { maxAmount: 0 },
    price: 0.0,
    contact:{}
  },
  onLoad:function(options){
    var that = this;
    var type = options.type;
    //初始化数据
    that.setData({
      room: { id: options.id },
      ticket: { id: options.id },
      tour: { id: options.id },
      type: type
    });
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  onShow: function () {
    let that = this;
    var startDate = wx.getStorageSync("startDate");
    var endDate = wx.getStorageSync("endDate");
    console.log("初始时间>>>" + startDate + endDate);
    if (!startDate || startDate == '' || !endDate || endDate == '') {
      //初始化当前时间
      // wx.clearStorageSync();
      startDate = Data.formatDate(new Date(), "yyyy-MM-dd");
      wx.setStorageSync("startDate", startDate);
      var tomorrow1 = new Date();
      tomorrow1.setDate((new Date()).getDate() + 1);
      var tomorrow = Data.formatDate(new Date(tomorrow1), "yyyy-MM-dd");
      endDate = tomorrow;
      wx.setStorageSync("endDate", tomorrow);
      console.log("如果为空，计算后时间>>>" + startDate + endDate);
    }

    var aDate, oDate1, oDate2, iDays
    aDate = endDate.split("-")
    console.log("aDate>>>:length-" + aDate.length + ",0-" + aDate[0] + ",1-" + aDate[1] + ",2-" + aDate[2])
    oDate1 = new Date();
    oDate1.setFullYear(aDate[0]);
    oDate1.setMonth(aDate[1] - 1);
    oDate1.setDate(aDate[2]);

    aDate = startDate.split("-")
    oDate2 = new Date();
    oDate2.setFullYear(aDate[0]);
    oDate2.setMonth(aDate[1] - 1);
    oDate2.setDate(aDate[2]);
    console.log("oDate2》》》", oDate2)
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24)    //把相差的毫秒数转换为天数  
    console.log("iDays》》》", iDays);
    //初始化日期
    this.setData({
      date: startDate,
      tomorrow: endDate,
      dates: iDays
    });
    //加载所有页面数据
    that.getData();
  },
  //事件处理函数
  bindViewTap: function () {
    var that = this;
    var startDate = that.data.date;
    var endDate = that.data.tomorrow;
    wx.navigateTo({
      url: '/pages/calender/index?startDate=' + startDate + "&endDate=" + endDate
    })
  },
  //加载日历价格
  getCanPrice: function (fnCallBack) {
    let that = this;
    var type = that.data.type;
    var url = "";
    var data = {};
    if (type == 'tour') {
      url = api.TourPrice;
      data['id'] = that.data.tour.id;
    } else if (type == 'hotel') {
      url = api.HotelPrice;
      data['id'] = that.data.room.id;
      data['startDate'] = that.data.date;
      data['endDate'] = that.data.tomorrow;
    } else {
      url = api.ScenePrice;
      data['id'] = that.data.ticket.id;
      data['startDate'] = that.data.date;
    }
    util.request(url, data).then(function (res) {
      if (res.code === '200') {
        //如果是线路价格，默认选中第一个
        if (res.datas.length > 0 && type == 'tour') {
          res.datas[0]["pick"] = true;
        }
        //设置到价格日历
        that.setData({
          canPrice: res.datas
        })
        //执行回调
        if (typeof fnCallBack == 'function') {
          fnCallBack(that);
        }
      }
    });
  },
  //加载优惠券
  getConpon: function () {
    var that = this;
    var url = api.CouponForUse;
    var data = {
      token: wx.getStorageSync("token"),
      type: that.data.type
    };
    util.request(url, data).then(function (res) {
      if (res.code === '200') {
        var couponList = res.datas;
        var total = that.data.total;
        for (var i = 0; i < couponList.length; i++) {
          if (total > couponList[i].minAmount) {
            couponList[i]['flag'] = true;
          }
        }
        var o = [];
        for (var j = 0; j < couponList.length; j++) {
          if (couponList[j].flag) {
            if (o.length == 0) {
              couponList[j]['checked'] = true;
            }
            o.push(couponList[j])
          }
        }
        that.setData({
          couponList: o,
          coupon: o.length > 0 ? o[0] : { maxAmount: 0 }
        })
      }
    });
  },
  //获取页面数据
  getData: function () {
    let that = this;
    var url = "";
    var data = {};
    var type = that.data.type;
    if (type == 'scene') {
      url = api.SceneTicketDetail;
      data['id'] = that.data.ticket.id
    } else if (type == 'hotel') {
      url = api.HotelRoomDetail;
      data['id'] = that.data.room.id;
      data['startDate'] = wx.getStorageSync("startDate");
      data['endDate'] = wx.getStorageSync("endDate");
    } else {
      url = api.TourDetail;
      data['id'] = that.data.tour.id
    }
    //发起请求，获取商品数据
    util.request(url, data).then(function (res) {
      if (res.code === '200') {
        that.setData({
          room: res.datas.room ? res.datas.room : null,
          ticket: res.datas.ticket ? res.datas.ticket : null,
          tour: res.datas.tour ? res.datas.tour : null,
          images: res.datas.images ? res.datas.images : null,
          imageNumber: res.datas.images ? res.datas.images.length : null
        });
        //设置
        var title = that.data.type == 'scene' ? res.datas.ticket.ticketName : (that.data.type == 'hotel' ? res.datas.room.type : res.datas.tour.routeName);
        wx.setNavigationBarTitle({
          //页面标题为路由参数
          title: title
        });
        // var info = that.data.type == 'scene' ? res.datas.ticket.info : (that.data.type == 'hotel' ? res.datas.room.info : res.datas.tour.introduction);
        // WxParse.wxParse('content', 'html', Base64util.Base64.decode(info, "utf-8"), that, 5);
      }
    });
    //获取邮费
    util.request(api.GetTransFee).then(function (res) {
      if (res.code === '200') {
        that.setData({
          transFee: res.datas
        });
        //油费保存到本地
        wx.setStorageSync("transFee", res.datas);
      }
    });
    //获取价格日历
    that.getCanPrice(that.caclPrice);
    //获取优惠卷
    that.getConpon();
    //计算当前商品总价
    // that.caclPrice(that);
  },
  //计算当前商品总价
  caclPrice(that) {
    var total = 0;
    //类型
    var type = that.data.type;
    var number = that.data.number;
    //日历价格
    var canPrice = that.data.canPrice;
    if ("hotel" == type) {
      var temp = 0;
      for (var i = 0; i < canPrice.length - 1; i++) {
        temp = util.formatFloat(canPrice[i].price + temp, 2);
      }
      total = util.formatFloat(temp * parseInt(number), 2);
    } else if ("scene" == type) {
      total = util.formatFloat(canPrice[0].price * parseInt(number), 2);
    } else {
      var index = 0;
      for (var k = 0; k < canPrice.length; k++) {
        if (canPrice[k].pick) {
          index = k;
        }
      }
      total = util.formatFloat(canPrice[index].price * parseInt(number), 2);
    }
    //扣除优惠券价格
    // var discount = 0;
    // for(var j=0;j<couponList.length;j++){
    //   if(couponList[i].check){
    //     discount = couponList[i].maxAmount;
    //   }
    // }
    // total = total>discount?util.formatFloat(total-discount,2):0;
    that.setData({
      total: total
    })


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function (options) {
    
  },
  fnAddNum: function () {
    var that = this;
    if (that.data.type == 'tour') {
      that.fnAddUser();
    }
    var number = that.data.number + 1;
    that.setData({
      number: number
    })
    //重新加载优惠券
    that.getConpon();
    //重新计算价格
    that.caclPrice(that);
  },
  fnMinNum: function () {
    var that = this;

    if (that.data.number < 2) {
      that.setData({
        number: 1,
      })

      return;
    }
    if (that.data.type == 'tour') {
      that.fnMinUser();
    }
    var number = that.data.number - 1;
    that.setData({
      number: number
    })
    //重新加载优惠券
    that.getConpon();
    that.caclPrice(that);
  },
  bindDateChange: function (e) {
    var that = this;
    var value = e.detail.value;
    that.setData({
      date: value
    })
  },
  fnOrder: function () {

    var that = this;
    var room = that.data.room;
    var ticket = that.data.ticket;
    var tour = that.data.tour;
    var number = that.data.number;
    var userList = that.data.userList;
    var type = that.data.type;
    var billInfo = that.data.billInfo;
    var remark = that.data.remark;
    var goodsId = "";
    var url = "";
    var couponId = that.data.coupon.id ? that.data.coupon.id : null;
    var token = wx.getStorageSync("token");
    var needBill = that.data.needBill;
    needBill = needBill ? 1 : 0;
    if (token == null || token == "") {
      wx.showModal({
        title: '您还未登录，现在去登录？',
        content: '',
        confirmText: "是",
        cancelText: "否",
        success: function (options) {
          if (options.confirm) {
            wx.navigateTo({
              url: '/pages/auth/register/register',
            })
          }
        }
      })
      return
    }
    if ("hotel" == type) {
      goodsId = room.id;
      url = api.HotelRoomOrder;
    } else if ("scene" == type) {
      goodsId = ticket.id;
      url = api.SceneTicketOrder;
    } else {
      goodsId = tour.id;
      url = api.TourOrder;
    }
    //校验非空 
    for (var i = 0; i < userList.length; i++) {
      var customerInfo = userList[i];
      if ( customerInfo.name == "" || customerInfo.idCard == "") {
        wx.showToast({
          title: "请完善出行人信息",
          duration: 1500,
          image: '/static/images/icon_error.png'
        });
        return;
      }
      //校验数据格式
      // if (!(/^1[3|4|5|8|7|9][0-9]\d{4,8}$/.test(customerInfo.tel))) {
      //   wx.showToast({
      //     title: '电话号码不正确',
      //     duration: 1500,
      //     image: "/static/images/icon_error.png"
      //   });
      //   return;
      // }
      if (!(/^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/.test(customerInfo.idCard))) {
        wx.showToast({
          title: '身份证号码错误',
          duration: 1500,
          image: "/static/images/icon_error.png"
        })
        return;
      }
    }
    if (!that.data.contact||!that.data.contact.name) {
      wx.showToast({
        title: '联系人为空',
        duration: 1500,
        image: "/static/images/icon_error.png"
      })
      return;
    }
    if (!(/^1[3|4|5|8|7|9][0-9]\d{4,8}$/.test(that.data.contact.tel))) {
      wx.showToast({
        title: '联系人号码错误',
        duration: 1500,
        image: "/static/images/icon_error.png"
      });
      return;
    }
    if (!that.data.check) {
      wx.showToast({
        title: '请同意用户协议',
        duration: 1500,
        image: "/static/images/icon_error.png"
      })
      return;
    }
    if (that.data.needBill) {
      if (!billInfo.companyName || billInfo.companyName == ''
        || !billInfo.code || billInfo.code == '' || !billInfo.address || billInfo.address == '') {
        wx.showToast({
          title: '请填写开票信息',
          duration: 1500,
          image: "/static/images/icon_error.png"
        });
        return
      }
    }

    var data = {
      token: token,
      userInfo: JSON.stringify(userList),
      id: goodsId,
      couponId: couponId,
      number: number,
      dates: that.data.dates,
      startDate: that.data.date,
      endDate: that.data.tomorrow,
      useDate: that.data.date,
      remark: remark,
      contactName:that.data.contact.name,
      contactTel:that.data.contact.tel
    }
    if (that.data.needBill) {
      data["companyName"] = billInfo.companyName;
      data['code'] = billInfo.code;
      data['address'] = billInfo.address;
    }
    //发起请求
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    util.request(url, data).then(function (res) {
      wx.hideLoading();
      if (res.code === '200') {
        wx.showModal({
          title: '预定成功，立即支付？',
          content: '',
          confirmText: "去支付",
          cancelText: "稍后再说",
          success: function (options) {
            if (options.confirm) {
              var url = "/pages/pay/pay?orderId=" + res.datas.id + "&price=" + res.datas.price + "&orderType=" + type + "&needBill=" + needBill;
              wx.navigateTo({
                url: url
              });
            } else {
              //跳转到我的订单
              url = "/pages/ucenter/order/pendorder?type=" + type;
              wx.navigateTo({
                url: url,
              })
            }
          }
        })

      }else if(res.code=='500'&&res.datas=='1'){
		  app.showLogin();
	  } else {
        wx.showModal({
          title: '预定失败，请重试',
          content: '',
          confirmText: "确定",
          cancelText: "取消",
          success: function (options) {
            if (options.confirm) {

            } else {

            }
          }
        })
      }
    });

  },
  fnInput: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var userList = that.data.userList;
    userList[index][e.currentTarget.id] = e.detail.value;
    that.setData({
      userList: userList
    })
  },
  fnInputContact:function(e){
    var that = this;
    var contact = that.data.contact;
    contact[e.currentTarget.id] = e.detail.value;
    that.setData({
      contact: contact
    })
  },
  previewImage: function () {
    var that = this;
    wx.previewImage({
      current: 1, // 当前显示图片的http链接  
      urls: that.data.images// 需要预览的图片http链接列表  
    })
  },
  //事件处理函数
  bindViewTap: function () {
    var that = this;
    var startDate = that.data.date;
    var endDate = that.data.tomorrow;
    console.log(startDate);
    console.log(endDate);
    wx.navigateTo({
      url: '../calender/index?startDate=' + startDate + "&endDate=" + endDate
    })
  },
  //增加一个用户信息
  fnAddUser: function (e) {
    var userList = this.data.userList;
    userList.push({
      id:"",
      name: "",
      tel: "",
      idCard: ""
    });
    this.setData({
      userList: userList
    })
  },
  //删除一个用户信息
  fnDelUser: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var userList = this.data.userList;
    userList.splice(index, 1);
    this.setData({
      userList: userList
    })
  },
  switchChange: function (e) {
    let that = this;
    this.setData({
      check: !that.data.check
    })
  },
  fnEmpty: function () { },
  //打开优惠券选择
  fnOpenCoupon: function (e) {
    this.setData({
      modalFlag: true
    })
  },
  //关闭优惠券选择
  fnClose: function (e) {
    this.setData({
      modalFlag: false
    })
  },
  radioChange: function (e) {
    var that = this;
    var couponList = that.data.couponList;
    var coupon = {};
    for (var i = 0; i < couponList.length; i++) {
      if (couponList[i].id == e.detail.value) {
        couponList[i].checked = true;
        coupon = couponList[i];
      } else {
        couponList[i].checked = false;
      }
    }
    that.setData({
      coupon: coupon,
      couponList: couponList
    })
  },
  fnMinUser: function () {
    let that = this;
    var userList = that.data.userList;
    userList.splice(userList.length - 1, 1);
    that.setData({
      userList: userList
    })
  },
  fnPick: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var canPrice = that.data.canPrice;
    for (var i = 0; i < canPrice.length; i++) {
      canPrice[i]["pick"] = false;
    }
    canPrice[index].pick = true;
    that.setData({
      canPrice: canPrice,
      date: canPrice[index].date
    })
    that.caclPrice(that);
  },
  switchBill: function (e) {
    let that = this;
    var needBill = !that.data.needBill;
    that.setData({
      needBill: needBill
    })
    // if(needBill){
    //   wx.navigateTo({
    //     url: '/pages/billInfo/index',
    //   })
    // }

  },
  fnInputBillInfo: function (e) {
    var id = e.currentTarget.id;
    var that = this;
    var billInfo = that.data.billInfo;
    billInfo['' + id] = e.detail.value;
    that.setData({
      billInfo: billInfo
    })
  },
  fnInputRemark: function (e) {
    var that = this;
    that.setData({
      remark: e.detail.value
    })
  },
  showRules: function (e) {
    wx.navigateTo({
      url: '/pages/declear/index',
    })
  },
  colorChan: function(e) {
    
    var that = this;
    //console.log(that.data.dateData[0]);
    console.log(that.data.index[0]);
    var addStatus = that.data.tabStatus;
    if (addStatus==0) {
      this.setData({
        tabclass: "background:#FFF9F4; border:1rpx solid #FFD7B9;",
        tabStatus: 1
      })
    }else {
      this.setData({
        tabclass: "",
        tabStatus: 0
      })
    }
  },
  fnDetail: function (e) {
    var content = e.currentTarget.dataset.content;
   
    wx.navigateTo({
      url: '/pages/shopdetail/index?content=' + Base64util.Base64.encode(content),
    })
  },
  declare: function () {
    wx.navigateTo({
      url: '/pages/declear/index',
    })
  },
  fnToChoose:function(){
    wx.navigateTo({
      url: '/pages/preOrder/chooseContacts/contacts?number='+this.data.number,
    })
  },
  editUser:function(e){
    var that=this
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index
    var name = e.currentTarget.dataset.name
    var idcard = e.currentTarget.dataset.idcard
    var telephone = e.currentTarget.dataset.telephone
    if(id==undefined||id==''){
return
    }
    wx.navigateTo({
      url: '/pages/perCenter/contactsNew/index?id=' + id + "&type=choose&index=" + index + "&name=" + name + "&idCard=" + idcard+"&telephone="+telephone
    })
  }
})